

class Node {
    constructor(element, next) {
        this.element = element
        this.next = next
    }
}

class LinkList {
    constructor(value, element) {
        this.head = null
        this.size = 0
    }

    add(index, element) {
        if (arguments.length === 1) {
            element = index
            index = this.size
        }
        if (index === 0) {
            let oldHead = this.head
            this.head = new Node(element, oldHead)
        } else {
            let preNode = this._getNode(index - 1)
            preNode.next = new Node(element, preNode.next)
        }
        this.size++
    }
    _getNode(index) {
        let i = 0
        let cur = this.head
        while (i !== index) {
            cur = cur.next
            i++
        }
        return cur
    }
    remove(index) {
        if (index === 0) {
            let cur = this.head
            if (this.head === null) return
            this.head = this.head.next
            this.size--
            return cur
        } else {
            let preNode = this._getNode(index - 1)
            if (!preNode) return
            let removeNode = preNode.next
            preNode.next = preNode.next.next
            this.size--
            return removeNode
        }
    }
    update(index, ele) {
        let cur = this._getNode(index)
        cur.element = ele
        return cur
    }

    getNode(index) {
        this._getNode(index)
    }
    reverse() { // 双双对比递归法 
        const next = (head) => {
            if (head == null || head.next == null) return head
            let newHead = next(head.next) // 两两交换  On
            head.next.next = head  // 新头的下一个指向老头
            head.next = null // 老头的下个为null
            return newHead
        }
        return next(this.head)
    }
    reverse() { //  依次倒推循环法   新头的下一个就是上一个新头
        let head = this.head
        if (head === null || head.next === null) return head
        let newHead = null;
        while (head) {
            let n = head.next  //  先保存 当前头之后的
            head.next = newHead  // 把新头的下一个 指向上一个新头
            newHead = head  // 新头为当前的
            head = n  //  老头的指针后移一位
        }
        return newHead

    }
}

let ll = new LinkList

// ll.add(1)
// ll.add(2)
// ll.add(3)
// ll.add(4)
// // ll.remove(2)
// console.dir(ll, { depth: 1000 })
// console.dir(ll.reverse(), { depth: 1000 })

class Queue {
    constructor() {
        this.ll = new LinkList
    }
    add(ele) {
        this.ll.add(ele)
    }
    peek() {
        return this.ll.remove(0)
    }
}


exports.Queue = Queue

